package com.db.test.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/flow")
public class ProcessController {

    @Autowired
    private RepositoryService repositoryService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private TaskService taskService;


    @RequestMapping(value = "/startFlow")
    @ResponseBody
    public String startFlow(@RequestParam("key") String key) {
        String pKey = StringUtils.isEmpty(key) ? "" : key;

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(pKey);

        return processInstance.getProcessInstanceId();
    }

    @RequestMapping(value = "/findUserTask")
    @ResponseBody
    private String findUserTask(@RequestParam("userid") String userid) {
        List<Task> taskList = taskService.createTaskQuery().taskAssignee(userid).list();
        JSONArray array = new JSONArray();
        for (Task task : taskList) {
            JSONObject object = new JSONObject();
            object.put("id", task.getId());
            object.put("name", task.getName());
            array.add(object);
        }

        return array.toJSONString();
    }

    @RequestMapping(value = "/completeTask")
    @ResponseBody
    private void completeTask(@RequestParam("taskid") String taskid, @RequestParam("code") String code) {
        Map<String, Object> param = new HashMap<>();
        param.put("code", code);
        taskService.complete(taskid, param);
    }


}
